# -*- coding: UTF-8 -*-
"""
KStocks 股票分析系统 - 主程序
"""

import sys
import warnings
from os.path import exists as file_exists
from files import custommodule,update, recommend, backtest, manager, analyze, trade

warnings.simplefilter(action='ignore', category=FutureWarning)

class App:
    """股票分析系统主应用类"""
    def __init__(self):
        self.title = "KStocks 股票分析系统 v1.0"
        self.menu_options = {
            "1": {"name": "股票数据更新", "func": update.menu},
            "2": {"name": "交易策略回测", "func": backtest.menu},
            "3": {"name": "自动智能荐股", "func": recommend.menu},
            "4": {"name": "股票诊断", "func": analyze.menu},
            "5": {"name": "股票管理", "func": manager.menu},
            "6": {"name": "模拟交易", "func": trade.menu},
            "0": {"name": "退出系统", "func": self.exit}
        }

    def display_title(self):
        """显示应用标题"""
        width = 40
        print("\n" + "=" * width)
        print(f"{self.title:^{width}}")
        print("=" * width)

    def display_menu(self):
        """显示主菜单"""
        print("\n请选择操作：")
        for key, item in self.menu_options.items():
            print(f"    {key}. {item['name']}")
        print("-" * 20)

    def handle_choice(self, choice):
        """处理用户选择"""
        if choice in self.menu_options:
            try:
                self.menu_options[choice]["func"]()
            except Exception as e:
                print(f"\n⚠️ 操作失败: {str(e)}\n")
        else:
            print("\n⚠️ 输入错误，请输入 0-4 之间的数字\n")

    def exit(self):
        """退出应用"""
        print("\n感谢使用 KStocks 系统，再见！\n")
        raise SystemExit

    def run(self):
        """运行应用主循环"""
        self.display_title()
        while True:
            self.display_menu()
            choice = input("请输入数字选择：").strip()
            self.handle_choice(choice)

def main():
    """程序入口点"""
    try:
        if not file_exists('db_file.db'):
            print("程序首次运行，请仔细阅读readme.txt文件。")
            print("开始创建数据库...")
            custommodule.create_tables_if_not_exist()
            license_key = input("本程序股票数据源为'麦蕊智数'，请输入licence证书：")
            config = custommodule.ConfigManager()
            config.set_value('licence', license_key)
            update.full_update()
            print("程序初始化完成，欢迎使用 KStocks 系统！")

        app = App()
        app.run()
    except KeyboardInterrupt:
        print("\n程序被用户中断，正在退出...")

    except Exception as e:
        print(f"\n{str(e)}")

    finally:
        print("程序已退出！")



if __name__ == '__main__':
    main()
